Create API Gateway using AWS CDK

Create API Gateway using AWS CDK

Clock Icon2024.04.14

Introduction

In this blog post, I will explain how to a create an API endpoint using API Gateway and AWS CDK. We will use AWS CDK Toolkit, which is a command line tool for interacting with CDK apps. We can use AWS CDK Toolkit to create, manage and deploy AWS CDK projects. AWS CDK supports Typescript, Javascript, Python, Java, C#/.Net and Go.

Prerequisites

  • Knowledge of Typescript/Javascript, NodeJS
  • AWS Account
  • AWS CDK v2

Setup AWS CDK project

In this project, we are going to create a function which will fetch all the timezones from the external URL -> https://worldtimeapi.org/api/timezone. We will create a lambda handler function to deploy our function that fetches all the timezones.

We will create an API endpoint with method GET using API gateway and use our Lambda handler function to retrieve all the timezones,

Steps to create a CDK project

  1. mkdir cdk-apigateway : Create a directory called cdk-apigateway
  2. cd cdk-apigateway
  3. npx cdk init app --language typescript : Command to initialize a cdk project with language template typescript
  4. npx cdk ls : If the output is CdkApigatewayStack, then your cdk project setup is completed.

Lambda Handler Function

File : <cdk-apigateway/lambda/index.ts>


export const handler = async () => {
  try {
    const url = "https://worldtimeapi.org/api/timezone";
    const response = await fetch(url);
    const data = await response.json();
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  } catch (error) {
    console.error("Error fetching timezone data:", error);
    return {
      statusCode: 500,
      body: JSON.stringify({ message: "Error fetching timezone data." }),
    };
  }
};

Program to create cdk stack

File : <cdk-apigateway/lib/cdk-apigateway-stack.ts>


import * as cdk from "aws-cdk-lib";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as apigateway from "aws-cdk-lib/aws-apigateway";
import { Construct } from "constructs";

export class CdkApigatewayStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    /**
     * Stack of lambda function to get all the timezones
     */
    const getAllTimezonesFunction = new lambda.Function(
      this,
      "GetAllTimezonesFunction",
      {
        runtime: lambda.Runtime.NODEJS_18_X,
        handler: "index.handler",
        code: lambda.Code.fromAsset("lambda"),
      }
    );

    /**
     * API gateway stack
     */

    const api = new apigateway.RestApi(this, "MyApiGateway", {
      restApiName: "MyApi",
    });

    const getAllTimezonesResource = api.root.addResource("timezones");
    const getAllTimezonesIntegration = new apigateway.LambdaIntegration(
      getAllTimezonesFunction
    );
    getAllTimezonesResource.addMethod("GET", getAllTimezonesIntegration);

    new apigateway.Deployment(this, "MyApiGatewayDeployment", {
      api,
    });
  }
}
  1. Lambda Function Creation: The code creates a Lambda function named GetAllTimezonesFunction using the lambda.Function construct from the AWS CDK. This function is intended to retrieve all timezones. It's configured with the Node.js 18.x runtime and is deployed from the lambda directory as the function's code.
  2. API Gateway Configuration: The code sets up an API Gateway named MyApiGateway using the apigateway.RestApi construct. This API is given the name "MyApi".
  3. Resource and Integration: It defines a resource /timezones under the root of the API using api.root.addResource("timezones"). This resource is used to organize API endpoints. Then, it creates an integration between the /timezones resource and the GetAllTimezonesFunction Lambda function using apigateway.LambdaIntegration. This integration allows the API Gateway to forward requests to the Lambda function.
  4. Method Assignment: The code assigns the GET method to the /timezones resource by using getAllTimezonesResource.addMethod("GET", getAllTimezonesIntegration). This means that when a GET request is made to the /timezones endpoint of the API, it triggers the GetAllTimezonesFunction Lambda function.
  5. Deployment: Finally, the code deploys the API using apigateway.Deployment. This step is crucial for making the API accessible to clients. It ensures that the API configuration is propagated and deployed to the API Gateway service in AWS.

Results

Now that we have written our code to setup and create the API endpoint, we have to deploy the stack using the following commands.

  1. npx cdk bootstrap : Initializes the AWS environment, enabling smooth deployment of CDK stacks.
  2. npx cdk deploy : Command used to deploy AWS CDK stacks defined in the project, applying the changes to AWS infrastructure as specified in the code.

In the Outputs, you can see the endpoint is created as follows

After deploying, the API Gateway endpoint is created as follows

When we open the URL https://<apigateway_id>.execute-api.ap-northeast-1.amazonaws.com/prod/timezones

we can see the following result where all the timezones are displayed.

To access the URL, Navigate as follows in AWS console to see the Invoke URL

  1. API Gateway
  2. APIs
  3. MyApi 
  4. Stages
  5. Expand the stage prod > /timezones > GET

Conclusion

With the ability to define infrastructure as code, developers can efficiently manage and scale their AWS resources, ultimately streamlining the development process and enhancing overall project agility. By embracing modern tools like AWS CDK, developers can focus more on building innovative solutions while abstracting away the complexities of infrastructure management. AWS CDK offers a flexible and intuitive framework for building and deploying cloud-native applications. By combining the power of CDK with the scalability of API Gateway, developers can create robust APIs that meet the demands of modern web and mobile applications.

この記事をシェアする

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.